package com.zj.joke;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.jsoup.nodes.Element;

import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import cn.sharesdk.framework.ShareSDK;
import cn.waps.AppConnect;
import cn.waps.br;

import com.activeandroid.ActiveAndroid;
import com.zj.joke.R;
import com.zj.joke.adapter.RemoteCategoryAdapter;
import com.zj.joke.db.DBCategory;
import com.zj.joke.db.DBItem;
import com.zj.joke.db.DBStoreItem;
import com.zj.joke.form.RemoteCategoryItem;
import com.zj.joke.util.ActivityUtils;
import com.zj.joke.util.CategoryUtils;
import com.zj.joke.util.RemoteCategoryUtils;
import com.zj.joke.view.CustomProgressDialog;
import com.zj.joke.view.QuitPopAd;

public class RemoteCategoryActivity extends ZJActivity implements
		OnItemClickListener, OnClickListener {
	private TextView mMoreTv;
	private TextView mSettingTv;
	private CustomProgressDialog mDialog;
	private GridView mGridview;
	private RemoteCategoryAdapter mRemoteCategoryAdapter;
	private Handler mHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		findViews();
		mHandler = new Handler();
		mDialog = CustomProgressDialog.createDialog(this);
		mDialog.setMessage("正在加载中...");
		mDialog.setCancelable(true);
		initWanpuData();
		new MyAsync().execute(Consts.BASE_URL);
	}

	private void initWanpuData() {
		AppConnect.getInstance(this);
		// AppConnect.getInstance("09f277ca386ee99cb4c910e09f562112", "default",
		// this);
		// 迷你广告调用方式
		// AppConnect.getInstance(this).setAdBackColor(Color.argb(50, 120, 240,
		// 120));//设置迷你广告背景颜色
		// AppConnect.getInstance(this).setAdForeColor(Color.YELLOW);//设置迷你广告文字颜色
		LinearLayout miniLayout = (LinearLayout) findViewById(R.id.showMiniAd);
		AppConnect.getInstance(this).showMiniAd(this, miniLayout, 10);// 10秒刷新一次
		// 预加载插屏广告内容（仅在使用到插屏广告的情况，才需要添加）//退出时用
		AppConnect.getInstance(this).initPopAd(this);
		// 预加载自定义广告内容（仅在使用了自定义广告、抽屉广告或迷你广告的情况，才需要添加）
		AppConnect.getInstance(this).initAdInfo();
	}

	private void findViews() {
		mMoreTv = (TextView) findViewById(R.id.mainMore);
		mMoreTv.setOnClickListener(this);
		mSettingTv = (TextView) findViewById(R.id.mainSetting);
		mSettingTv.setOnClickListener(this);
		mGridview = (GridView) findViewById(R.id.gridview);
		mRemoteCategoryAdapter = new RemoteCategoryAdapter(mContext);
		mGridview.setAdapter(mRemoteCategoryAdapter);
	}

	private void init(List<RemoteCategoryItem> remoteCategoryItems) {
		ActiveAndroid.beginTransaction();
		try {
			for (int i = 0; i < remoteCategoryItems.size(); i++) {
				List<DBCategory> localList = DBCategory.getDBCategorys();
				if (localList != null && localList.size() > 0) {
					boolean isFind = false;
					for (DBCategory category : localList) {
						String temp = remoteCategoryItems.get(i).getCategory();
						if (temp.equals(category.category)) {
							isFind = true;
							break;
						}
					}
					if (!isFind) {
						DBCategory dbCategory = new DBCategory();
						dbCategory.unreadnum = 0;
						dbCategory.image_id = R.drawable.bluefaces_35;
						dbCategory.category = remoteCategoryItems.get(i)
								.getCategory();
						dbCategory.count = remoteCategoryItems.get(i)
								.getCount();
						dbCategory.url = remoteCategoryItems.get(i).getUrl();
						dbCategory.save();
					}
				} else {
					DBCategory dbCategory = new DBCategory();
					dbCategory.unreadnum = 0;
					dbCategory.image_id = R.drawable.bluefaces_35;
					dbCategory.category = remoteCategoryItems.get(i)
							.getCategory();
					dbCategory.count = remoteCategoryItems.get(i).getCount();
					dbCategory.url = remoteCategoryItems.get(i).getUrl();
					dbCategory.save();
				}
			}
			ActiveAndroid.setTransactionSuccessful();
			mRemoteCategoryAdapter.setRemoteCategoryItems(remoteCategoryItems);
		} finally {
			ActiveAndroid.endTransaction();
		}
	}

	class MyAsync extends AsyncTask<String, Void, List<RemoteCategoryItem>> {
		@Override
		protected void onPreExecute() {
			mDialog.show();
			super.onPreExecute();
		}

		@Override
		protected List<RemoteCategoryItem> doInBackground(String... params) {
			List<RemoteCategoryItem> remoteCategoryItems;
			remoteCategoryItems = RemoteCategoryUtils.getCategorys(params[0]);
			return remoteCategoryItems;
		}

		@Override
		protected void onPostExecute(List<RemoteCategoryItem> result) {
			// final List<RemoteCategoryItem> temp = result;
			mGridview.setOnItemClickListener(RemoteCategoryActivity.this);
			// if (temp != null) {
			// mHandler.post(new Runnable() {
			//
			// @Override
			// public void run() {
			init(result);
			// }
			// });
			// }

			if (mDialog != null && mDialog.isShowing()) {
				mDialog.dismiss();
			}
			super.onPostExecute(result);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		// 在本例中arg2=arg3
		RemoteCategoryItem navigationItem = (RemoteCategoryItem) parent
				.getItemAtPosition(position);
		setTitle(navigationItem.getCategory());
		Intent intent = new Intent();
		intent.setClass(this, RemoteContentActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("item", navigationItem);
		intent.putExtras(bundle);
		startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.mainMore:
			Intent intent = new Intent();
			intent.setClass(RemoteCategoryActivity.this, MoreActivity.class);
			startActivity(intent);
			overridePendingTransition(R.anim.push_left_in,
					R.anim.push_right_out);
			break;
		case R.id.mainSetting:
			Intent intent2 = new Intent();
			intent2.setClass(RemoteCategoryActivity.this, SettingActivity.class);
			startActivity(intent2);
			overridePendingTransition(R.anim.push_right_in,
					R.anim.push_left_out);
			break;
		}
	}

	@Override
	public void onBackPressed() {
		// Dialog alertDialog = new AlertDialog.Builder(this).setTitle("提示")
		// .setMessage("确定要退出吗？")
		// .setNegativeButton("取消", new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// }
		// })
		// .setPositiveButton("确定", new DialogInterface.OnClickListener() {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// AppConnect.getInstance(mContext).close();
		// ShareSDK.stopSDK(mContext);
		// ActivityUtils.getInstance().CloseAll();
		// }
		// }).create();
		// alertDialog.show();
		QuitPopAd.getInstance().show2(this);
	}

	@Override
	protected void onDestroy() {
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}
}
